package vn.vfriends.vbox.service.impl;

import java.util.List;
import javax.annotation.PostConstruct;
import javax.ejb.Stateless;
import javax.inject.Inject;
import javax.ws.rs.client.Client;
import javax.ws.rs.client.ClientBuilder;
import javax.ws.rs.client.Entity;
import javax.ws.rs.client.WebTarget;
import javax.ws.rs.core.GenericType;
import javax.ws.rs.core.MediaType;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import vn.vfriends.vbox.model.Account;
import vn.vfriends.vbox.rest.ApiConfig;
import vn.vfriends.vbox.rest.Authenticator;
import vn.vfriends.vbox.service.AccountService;

/**
 *
 * @author tuancn
 */
@Stateless
public class AccountServiceImpl implements AccountService {

    private static final Logger logger = LoggerFactory.getLogger(AccountServiceImpl.class);
    
    private Client client;
    
    @Inject @ApiConfig("API_URL")
    private String apiUrl;
    
    @Inject @ApiConfig("API_USER")
    private String apiUser;
    
    @Inject @ApiConfig("API_PASSWORD")
    private String apiPassword;
    
    @PostConstruct
    private void init() {
        client = ClientBuilder.newClient().register(new Authenticator(apiUser, apiPassword));
    }
    
    @Override
    public List<Account> findByUserId(Integer userId) {
        WebTarget target = client.target(apiUrl + "/accounts")
                .path("user/" + userId);
        return target.request().get(new GenericType<List<Account>>() {});
    }
    
    @Override
    public Account findByName(Integer userId, String name) {
        WebTarget target = client.target(apiUrl + "/accounts")
                .queryParam("userId", userId).queryParam("name", name);
        return target.request().get(Account.class);
    }

    @Override
    public void remove(Integer id) {
        WebTarget target = client.target(apiUrl + "/accounts")
                .path(id.toString());
        target.request().delete();
    }

    @Override
    public Account register(Integer userId, Account account) {
        WebTarget target = client.target(apiUrl + "/accounts").path("userid/" + userId);
        
        Entity<Account> entity = Entity.entity(account, MediaType.APPLICATION_XML);
        return target.request().post(entity, Account.class);
    }
    
}
